<template>
  <div class="edit-page-wrap">
    <Head title="基本信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="edit-form-wrap"
        >
          <el-form-item label="任务名称" prop="name">
            <el-input
              v-model.trim="ruleForm.name"
              placeholder="请输入任务名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
        </el-form>
        <Combination
          ref="comCouponRef"
          class="task-wrap"
          :items="comItem"
          :comData="ruleForm.comData"
          :rules="comRules"
          :size="10"
          :isTips="true"
        ></Combination>
        <el-form
          ref="ruleFormRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="edit-form-wrap"
        >
          <el-form-item label="发放目标" prop="targetType" class="has-tips">
            <el-radio-group
              v-model="ruleForm.targetType"
              v-for="(item, index) in TARGET_TYPE"
              :key="index"
              @change="handleTargetType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div v-if="ruleForm.targetType" class="tip">
              <div class="icon"></div>
              {{ getTargetTypeTip() }}
            </div>
          </el-form-item>
          <el-form-item
            label=""
            prop="treeVehicles"
            v-if="ruleForm.targetType == '0'"
          >
            <QcTree
              ref="treeVehiclesRef"
              :data="optionsS.vehicle"
              :showCheckbox="true"
              :checkStrictly="true"
              :setCheckedKeys="ruleForm.treeVehicles"
              @handleCheck="handleCheckVehicles"
            ></QcTree>
          </el-form-item>
          <el-form-item
            label=""
            prop="treeLabels"
            v-if="ruleForm.targetType == '1'"
          >
            <QcTree
              ref="treeLabelRef"
              :data="optionsS.label"
              :showCheckbox="true"
              :setCheckedKeys="ruleForm.treeLabels"
              @handleCheck="handleCheckLabel"
            ></QcTree>
          </el-form-item>
          <el-form-item label="" v-if="ruleForm.targetType == '2'">
            <el-button type="primary" plain @click="clickUploadUser"
              >批量导入</el-button
            >
          </el-form-item>
          <el-form-item prop="importUsers" v-if="ruleForm.targetType == '2'">
            <el-input
              v-model.trim="ruleForm.importUsers"
              placeholder="请输入用户账号"
              type="textarea"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="发放模式">
      <template #content>
        <el-form
          ref="ruleFormRef2"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="edit-form-wrap"
        >
          <el-form-item label="选择模式" prop="executeType">
            <el-radio-group
              v-model="ruleForm.executeType"
              v-for="(item, index) in EXECUTE_TYPE"
              :key="index"
              @change="handleTargetType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="执行时间"
            prop="nextTime"
            v-if="ruleForm.executeType == 1"
          >
            <div class="time-wrap">
              <el-date-picker
                v-model="ruleForm.nextTime1"
                value-format="YYYY-MM-DD"
                popper-class="qc-date"
                placeholder="请选择日期"
                type="date"
                @change="handleTime"
              />
            </div>
            <div class="time-wrap time-wrap1">
              <el-time-select
                v-model="ruleForm.nextTime2"
                start="00:00"
                step="00:10"
                end="23:50"
                placeholder="请选择时间"
                @change="handleTime"
              />
            </div>
          </el-form-item>
          <el-form-item
            label="总执行次数"
            prop="totalCount"
            v-if="ruleForm.executeType == 2"
          >
            <el-input
              v-model.trim="ruleForm.totalCount"
              placeholder="请输入总执行次数"
              maxlength="9"
              clearable
            />
          </el-form-item>
          <el-form-item
            label=""
            prop="executePeriod"
            v-if="ruleForm.executeType == 2"
          >
            <el-radio-group
              v-model="ruleForm.executePeriod"
              v-for="(item, index) in EXECUTE_PERIOD"
              :key="index"
              @change="changeExecutePeriod"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label=""
            prop="executeTime"
            v-if="ruleForm.executeType == 2 && ruleForm.executePeriod == '0'"
          >
            <div class="edit-date-wrap">
              <el-time-select
                v-model="ruleForm.executeTime"
                start="00:00"
                step="00:10"
                end="23:50"
                placeholder="请选择时间"
              />
            </div>
          </el-form-item>
          <div
            class="time-wrap"
            style="display: flex"
            v-if="ruleForm.executeType == 2 && ruleForm.executePeriod == '1'"
          >
            <el-form-item label="" prop="executeWeek">
              <qc-select
                class="weekData"
                :value="ruleForm.executeWeek"
                :options="WEEK"
                placeholder="请选择星期"
                @change="handleWeek"
              >
              </qc-select>
            </el-form-item>
            <el-form-item
              label=""
              prop="executeTime"
              style="margin-left: -110px"
            >
              <div class="edit-date-wrap">
                <el-time-select
                  v-model="ruleForm.executeTime"
                  start="00:00"
                  step="00:10"
                  end="23:50"
                  placeholder="请选择时间"
                />
              </div>
            </el-form-item>
          </div>
          <!-- <div class="has-tips"> -->
          <div
            class="time-wrap"
            style="display: flex"
            v-if="ruleForm.executeType == 2 && ruleForm.executePeriod == '2'"
          >
            <el-form-item label="" prop="executeDate">
              <qc-select
                class="weekData"
                :value="ruleForm.executeDate"
                :options="optionsS.date"
                placeholder="请选择日期"
                @change="handleDate"
              >
              </qc-select>
            </el-form-item>
            <el-form-item
              label=""
              prop="executeTime"
              style="margin-left: -110px"
            >
              <div class="edit-date-wrap">
                <el-time-select
                  v-model="ruleForm.executeTime"
                  start="00:00"
                  step="00:10"
                  end="23:50"
                  placeholder="请选择时间"
                />
              </div>
            </el-form-item>
          </div>
          <el-form-item
            label=""
            v-if="ruleForm.executeType == 2 && ruleForm.executePeriod == '2'"
            class="has-tips"
          >
            <div class="tip">
              <div class="icon"></div>
              <span
                >选择的日期在某月份无该日期时，则跳过该月的执行，示例：选择30号，2月份不执行该任务</span
              >
            </div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
    <ImportDialog ref="importDialogRef" @user-data="userData"></ImportDialog>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import Combination from '@/components/combination/combination.vue';
import ImportDialog from '@/components/qcDialog/importDialog.vue';
import { FormRules, FormInstance } from 'element-plus';
import { queryDicByParent } from '@/service/apis/api';
import { queryVehicleWhite, queryLabelListByName } from '@/service/apis/org';
import {
  queryActivity,
  saveTask,
  updateTask,
  getTaskById,
} from '@/service/apis/market';
import {
  TARGET_TYPE,
  EXECUTE_TYPE,
  EXECUTE_PERIOD,
  WEEK,
} from '@/utils/dictionaries';
import { IS_INT, IS_INT_0, NO_CHINESE_COMMA } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();
const ruleFormRef2 = ref<FormInstance>();
const comCouponRef = ref();
const importDialogRef = ref();
const treeVehiclesRef = ref();

const optionsS = reactive({
  executePeriod: [] as any,
  vehicle: [] as any,
  label: [] as any,
  date: [] as any,
  coupons: [] as any,
});

const dateDate = Array.from({ length: 31 }, (_, i) => 1 + i);
dateDate.forEach((value: any) => {
  optionsS.date.push({
    label: value,
    value: value,
  });
});

queryDicByParent({
  listDtos: ['stationTargetType'],
}).then((res: any) => {
  if (res) {
    optionsS.executePeriod = res.executePeriod;
  }
});

// 获取下拉优惠券
const getCouponList = () => {
  queryActivity({}).then((res: any) => {
    optionsS.coupons = res.map((item: any) => {
      return { label: item.name, value: item.id, count: item.restCount };
    });
    nextTick(() => {
      comCouponRef.value?.setOptions(0, 0, optionsS.coupons);
      comCouponRef.value?.setItemOption(optionsS.coupons, 0);
      if (id) {
        ruleForm.comData.forEach((item: any, index: number) => {
          comCouponRef.value?.setOptions(index, 0, optionsS.coupons);
          comCouponRef.value?.setValue(index, 'couponName', item.couponName);
          const cobj = optionsS.coupons.find(
            (temp: any) => temp.value === item.couponId
          );
          if (cobj) {
            comCouponRef.value?.setValue(index, 'count', cobj.count);
          }
        });
      }
    });
  });
};

// 获取车辆机构
const getVehicle = () => {
  queryVehicleWhite({}).then((res: any) => {
    if (res) {
      optionsS.vehicle = res;
    }
  });
};

// 获取标签
const getLabel = () => {
  queryLabelListByName({}).then((res: any) => {
    if (res) {
      optionsS.label = res.listMap;
    }
  });
};

const getTargetTypeTip = () => {
  if (ruleForm.targetType === '0') {
    return '选定企业后，该企业所有用户均为发放目标，含任务执行前新增的用户';
  } else if (ruleForm.targetType === '1') {
    return '选定标签后，该标签内所有均为发放目标，标签用户添加、删除会同步更新';
  } else if (ruleForm.targetType === '2') {
    return `注：请输入用户的账号，多个账号之间用英文‘,’隔开`;
  }
  return '';
};

const ruleForm: any = reactive({
  name: '', // 任务名称

  couponDetails: [] as any, // 优惠券列表

  targetType: '0', // 发放目标

  targetIds: '', // 执行目标ids ,号分隔
  treeVehicles: [] as any,
  treeLabels: [] as any,
  importUsers: '', // 导入或编辑的用户数据

  executeType: 0, // 选择模式

  nextTime: '', // 发放时间
  nextTime1: '',
  nextTime2: '',

  totalCount: '', // 总发放次数
  executePeriod: '0', // 执行周期
  executeTime: '', // 发放时间
  executeWeek: undefined as unknown, // 发放周几
  executeDate: undefined as unknown, // 发放哪天
});

const checkTreeVehicles = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeVehiclesRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的用户企业（车辆机构）'));
  }
  callback();
};
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  targetType: [
    { required: true, message: '请选择发放目标', trigger: ['blur', 'change'] },
  ],
  treeVehicles: [
    { required: true, message: '请选择企业', trigger: ['blur', 'change'] },
    { validator: checkTreeVehicles, trigger: ['blur', 'change'] },
  ],
  treeLabels: [
    { required: true, message: '请选择标签', trigger: ['blur', 'change'] },
  ],
  importUsers: [
    {
      required: true,
      message: '请导入或输入用户',
      trigger: ['blur', 'change'],
    },
    { pattern: NO_CHINESE_COMMA, message: '不能输入中文逗号', trigger: 'blur' },
  ],
  executeType: [
    { required: true, message: '请选择模式', trigger: ['blur', 'change'] },
  ],
  nextTime: [
    { required: true, message: '请选择执行时间', trigger: ['blur', 'change'] },
  ],
  totalCount: [
    { required: true, message: '请输入总发放次数', trigger: 'blur' },
    {
      pattern: IS_INT_0,
      message: '请输入正确总发放次数，整数',
      trigger: 'blur',
    },
  ],
  executePeriod: [
    { required: true, message: '请选择执行周期', trigger: ['blur', 'change'] },
  ],
  executeTime: [
    { required: true, message: '请选择时间', trigger: ['blur', 'change'] },
  ],
  executeWeek: [
    { required: true, message: '请选择星期', trigger: ['blur', 'change'] },
  ],
  executeDate: [
    { required: true, message: '请选择日期', trigger: ['blur', 'change'] },
  ],
});

const getCouponLabel = () => {
  let arr: any = [];
  for (let i = 0; i < 10; i++) {
    arr[i] = `优惠券${i + 1}`;
  }
  return arr;
};
const comItem = reactive([
  {
    comName: 'select',
    label: '优惠券1',
    labels: getCouponLabel(),
    labelWidth: 100,
    prop: 'couponId',
    width: 180,
    isOnly: true,
    tips: '当前库存：',
    tipKey: 'count',
    props: {
      remote: true,
      filterable: true,
      options: optionsS.coupons,
      change: (index: number, form: any) => {
        console.log('form----', form);
        const obj = form.data[index];
        if (obj.couponId) {
          const cobj = optionsS.coupons.find(
            (item: any) => item.value === obj.couponId
          );
          obj.count = cobj.count;
          obj.couponName = cobj.label;
        } else {
          obj.count = '';
          obj.couponName = '';
        }
        if (obj.couponCount) {
          comCouponRef.value?.validateField(`data.[${index}][couponCount]`);
        }
      },
    },
  },
  {
    comName: 'input',
    label: '',
    labelWidth: 0,
    prop: 'couponCount',
    width: 110,
    props: {
      append: '张',
      maxlength: 3,
      type: 'number',
      placeholder: '正整数',
    },
  },
]);

const checkCouponCount = (rule: any, value: any, callback: any) => {
  const index = rule.field.split('.[')[1].split(']')[0];
  const obj = comCouponRef.value?.getData();
  if (obj[index].couponId && Number(value) > Number(obj[index].count)) {
    callback(new Error('不能大于库存'));
  }
  console.log('222----', rule, index, value);

  callback();
};
const comRules = reactive<FormRules>({
  couponId: [
    { required: true, message: '请选择优惠券', trigger: ['blur', 'change'] },
  ],
  couponCount: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入正整数',
      trigger: 'blur',
    },
    { validator: checkCouponCount, trigger: 'blur' },
  ],
});

const handleTargetType = (val: any) => {
  if (val === '0' && optionsS.vehicle.length === 0) {
    getVehicle();
  } else if (val === '1' && optionsS.label.length === 0) {
    getLabel();
  }
};

const handleCheckVehicles = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeVehicles = checkedChildData;
};
const handleCheckLabel = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeLabels = checkedChildData;
};

const clickUploadUser = () => {
  importDialogRef.value?.show();
};
const userData = (data: any) => {
  ruleForm.importUsers = data;
};

const handleTime = () => {
  if (ruleForm.nextTime1 && ruleForm.nextTime2) {
    ruleForm.nextTime = `${ruleForm.nextTime1} ${ruleForm.nextTime2}:00`;
  } else {
    ruleForm.nextTime = '';
  }
};

const changeExecutePeriod = (e: any) => {
  ruleForm.executeTime = '';
  ruleForm.executeDate = undefined as unknown;
  ruleForm.executeWeek = undefined as unknown;
  const timer = setTimeout(() => {
    ruleFormRef2.value?.clearValidate('executeTime');
    clearTimeout(timer);
  });
};

const handleWeek = (e: any) => {
  ruleForm.executeWeek = e;
};
const handleDate = (e: any) => {
  ruleForm.executeDate = e;
};

if (id) {
  getTaskById(id).then((res: any) => {
    if (res) {
      for (const key in ruleForm) {
        if (res[key]) {
          ruleForm[key] = res[key];
        }
      }
      ruleForm.targetType = String(res.targetType);
      ruleForm.executePeriod = String(res.executePeriod);
      if (res.executePeriod === 1) {
        ruleForm.executeWeek = String(res.executeWeek);
      }
      if (ruleForm.targetType === '0') {
        ruleForm.treeVehicles = res.targetIds.split(',');
        getVehicle();
      } else if (ruleForm.targetType === '1') {
        ruleForm.treeLabels = res.targetIds.split(',');
        getLabel();
      } else if (ruleForm.targetType === '2') {
        ruleForm.importUsers = res.targetIds;
      }
      ruleForm.comData = [];
      res.couponDetails.forEach((item: any, index: number) => {
        ruleForm.comData.push({
          couponId: item.couponId,
          couponCount: item.couponCount,
          couponName: item.couponName,
        });
      });
      getCouponList();
      ruleForm.nextTime1 = res.nextTime.substring(0, 10);
      ruleForm.nextTime2 = res.nextTime.substring(11, 16);
    }
  });
} else {
  getCouponList();
  getVehicle();
}

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value || !ruleFormRef1.value || !ruleFormRef2.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
  }

  try {
    await Promise.all([comCouponRef.value.validate()]);
  } catch (fields: any) {
    flag = false;
    for (const key in fields) {
      if (fields[key] && flag) {
        comCouponRef.value.scrollToField(key);
        break;
      }
    }
  }

  await Promise.all([
    ruleFormRef1.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef2.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef1.value.scrollToField(key);
        ruleFormRef2.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  const form = { ...ruleForm };
  if (form.targetType == '0') {
    // form.targetIds = form.treeVehicles.toString();
    const arr: any = [];
    const treeOrg = treeVehiclesRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        arr.push(item.id);
      }
    });
    form.targetIds = arr.toString();
  } else if (form.targetType == '1') {
    form.targetIds = form.treeLabels.toString();
  } else if (form.targetType == '2') {
    form.targetIds = form.importUsers;
  }
  if (form.executeType === 0) {
    form.nextTime = null;
    delete form.nextTime1;
    delete form.nextTime2;
    form.totalCount = '';
    form.executePeriod = '';
    form.executeTime = '';
    form.executeWeek = '';
    form.executeDate = '';
  } else if (form.executeType === 1) {
    form.totalCount = '';
    form.executePeriod = '';
    form.executeTime = '';
    form.executeWeek = '';
    form.executeDate = '';
  } else if (form.executeType === 2) {
    form.nextTime = null;
    delete form.nextTime1;
    delete form.nextTime2;
  }
  form.couponDetails = [];
  const obj = comCouponRef.value?.getData();
  obj.forEach((item: any) => {
    form.couponDetails.push({
      couponId: item.couponId,
      couponCount: item.couponCount,
      couponName: item.couponName,
    });
  });
  console.log('rr----', form);
  if (id) {
    form.id = id;
    updateTask(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    saveTask(form).then((res: any) => {
      emit('clear-cache');
      router.replace({
        name: 'couponRecordList',
      });
    });
  }
};
</script>

<style lang="scss" scoped>
.time-wrap {
  display: flex;
  :deep(.el-select-v2),
  :deep(.el-input),
  :deep(.el-select),
  :deep(.el-input__wrapper) {
    width: 135px !important;
  }
}
.time-wrap1 {
  margin-left: 30px;
}
.task-wrap {
  :deep(.el-form-item:first-child) {
    .el-form-item__content,
    .el-form-item__error {
      padding-left: 24px !important;
    }
  }
}
</style>